//
//  WmcUploadQueueDBManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/1.
//

import Foundation
import YPBedrock

// MARK: - 扩展WmcUploadQueueDBManager + WmcDBProtocol

extension WmcUploadQueueDBManager: WmcDBProtocol {
    static var tableName: String {
        guard let userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !userId.isEmpty else {
            return ""
        }
        let name = "upload_queue_\(userId)"
        return name
    }
    
    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(),
            .varchar(name: "uuid"),
            .varchar(name: "photo_path"),
            .varchar(name: "watermark_type"),
            .varchar(name: "watermark_info"),
            .real(name: "take_photo_time"),
        ]
    }
}

// MARK: - [WmcUploadQueueDBManager]

struct WmcUploadQueueDBManager {
    
    /// 保存待上传的图片
    /// - Parameters:
    ///   - model: 图片model
    ///   - resultBlock: 结果
    static func insert(model: WmcUploadImageModel,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        let tableName = WmcUploadQueueDBManager.tableName
        if tableName.isEmpty {
            resultBlock?(false)
            return
        }

        let dataList: [WmcDBManager.InsertData] = [
            .init(column: Self.dataType[1], value: model.uuid),
            .init(column: Self.dataType[2], value: model.photoPath),
            .init(column: Self.dataType[3], value: model.watermarkType),
            .init(column: Self.dataType[4], value: model.watermarkInfo),
            .init(column: Self.dataType[5], value: model.takePhotoTime),
        ]

        WmcDBManager.shared.insertData(tableName: tableName, insertData: dataList, resultBlock: resultBlock)
    }
    
    /// 查询待上传的图片
    /// - Parameter resultBlock: 结果
    static func query(resultBlock: YPBlock.OneParam<[WmcUploadImageModel]>? = nil) {
        let tableName = WmcUploadQueueDBManager.tableName
        if tableName.isEmpty {
            resultBlock?([])
            return
        }

        WmcDBManager.shared.searchCustomData(tableName: tableName) { list in
            var result: [WmcUploadImageModel] = []
            list.forEach { data in
                if let model = WmcUploadImageModel.deserialize(from: data) {
                    result.append(model)
                }
            }
            resultBlock?(result)
        }
    }
    
    /// 删除待上传的图片
    /// - Parameters:
    ///   - model: 图片model
    ///   - resultBlock: 结果
    static func delete(model: WmcUploadImageModel,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        let tableName = WmcUploadQueueDBManager.tableName
        if tableName.isEmpty {
            resultBlock?(false)
            return
        }

        let condition = "where uuid = '\(model.uuid)'"

        WmcDBManager.shared.deleteCustomData(tableName: tableName, condition: condition, resultBlock: resultBlock)
    }
}
